package com.xnchat.pro.controller;

import cn.hutool.core.collection.ConcurrentHashSet;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mysql.cj.util.StringUtils;
import com.xnchat.pro.dto.Message;
import com.xnchat.pro.service.HandlerService;
import com.xnchat.pro.service.MessageService;
import com.xnchat.pro.service.RobotHandler;
import com.xnchat.pro.utils.MyDrrrUtil;
import com.xnchat.pro.utils.NormalReturn;
import com.xnchat.pro.vo.IndexVo;
import com.xnchat.pro.vo.MessageVO;
import com.xnchat.pro.vo.ReturnVo;
import com.xnchat.pro.vo.RoomVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/drrr")
public class DrrrMessage {
    private final static String STOP_FLAG = "STOP";
    private static final ConcurrentHashSet<String> idSet = new ConcurrentHashSet<>();
    private static final ConcurrentHashSet<String> roomSet_in = new ConcurrentHashSet<>();
    @Value("${user.admin.name}")
    private String adminName;
    MessageService messageService;

    HandlerService handlerService;
    private static boolean allFlag = false;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    @ResponseBody
    @GetMapping("/getByUserId")
    public String getMessage(@RequestParam("flag") String flag, @RequestParam("code") String code) {
        MyDrrrUtil drrrUtil = new MyDrrrUtil();
        String re;
        if (!code.contains("drrr-session-1")) {
            code = "drrr-session-1=" + code;
        }
        re = HttpRequest.get("https://drrr.com/json.php?update=" + System.currentTimeMillis())
                .header("Content-Type", "application/json")
                .header("cookie", code)
                .header("Connection", "keep-alive").timeout(90000)
                .execute().body();

        MessageVO messaged = JSONObject.parseObject(re, MessageVO.class);
        String roomId = messaged.getRoomId();
        if (roomSet_in.contains(roomId) && !STOP_FLAG.equals(flag)) {
            return "err:该房间已部署机器人";
        }
        roomSet_in.add(roomId);
        idSet.add(code);
        if (STOP_FLAG.equals(flag)) {
            roomSet_in.remove(roomId);
            idSet.remove(code);
        }


        allFlag = true;
        String finalCode = code;
        new Thread(
                () -> {
                    String time = "";
                    while (allFlag && idSet.contains(finalCode)) {
                        if (STOP_FLAG.equals(flag)) break;
                        String result = "";
                        try {
                            result = drrrUtil.getMessage(time, finalCode);
                        } catch (Exception e) {
                            logger.warn("房间自动关闭");
                            idSet.remove(finalCode);
                            roomSet_in.remove(messaged.getRoomId());
                            return;
                        }
                        if (StringUtils.isNullOrEmpty(result) || result.length() < 40) {
                            System.out.println("房间不存在：" + result);
                            break;
                        }
                        MessageVO messageVO = JSONObject.parseObject(result, MessageVO.class);
                        //更新下次查询时间
                        if (!time.equals(messageVO.getUpdate())) time = messageVO.getUpdate();
                        handlerService.saveMessage(messageVO, finalCode);
                    }
                    idSet.remove(finalCode);
                    roomSet_in.remove(messaged.getRoomId());
                    logger.info("！！！停止成功！！！" + finalCode);
                }
        ).start();
        BeanUtils.copyProperties("","");


        return "~~~正在启动~~~";
    }

    private static String beatFlag = "A";

    @ResponseBody
    @GetMapping("beat")
    public NormalReturn heartBeat(String code, String flag) throws InterruptedException {
        MyDrrrUtil drrrUtil = new MyDrrrUtil();
        beatFlag = flag;
        code = "drrr-session-1=" + code;
        while ("A".equals(beatFlag)) {
            drrrUtil.normalSend(code, "message=心跳");
            Thread.sleep(360 * 1000);
        }
        return NormalReturn.SUCCESS.addMessage("停止成功");
    }

    @ResponseBody
    @GetMapping("/oneStep")
    public NormalReturn oneStep() {
        return makeRobot(adminName+"#P[bFv]9.", "kanra", "日常上班摸鱼");
    }

    @ResponseBody
    @RequestMapping("/goToTF")
    public NormalReturn makeRobot(String var1, String var2, @RequestParam(required = false, defaultValue = "") String var3) {
        MyDrrrUtil drrrUtil = new MyDrrrUtil();
        NormalReturn normalReturn = drrrUtil.xnLogon(var1, var2);
        if (NormalReturn.FAIL_CODE == normalReturn.getCode() || StringUtils.isNullOrEmpty(var3)) {
            return normalReturn;
        }
        Map<String, Object> info = normalReturn.getInfo();
        String session = (String) info.get("cookie");
        String roomList = (String) info.get("roomList");
        IndexVo indexVo = JSON.parseObject(roomList, IndexVo.class);
        logger.info(indexVo.toString());
        List<RoomVo> rooms = indexVo.getRooms();
        String roomid = null;
        for (RoomVo r : rooms) {
            if (r.getName().contains(var3)) {
                roomid = r.getId();
                break;
            }
        }
        if (roomid != null) {
            try {
                logger.info(session);
                HttpRequest.get("https://drrr.com/room/?id=" + roomid)
                        .header("cookie", session)
                        .execute();
                HttpRequest.get("https://drrr.com/room/").header("cookie", session)
                        .execute();
                logger.info("进入房间成功");
                getMessage("Yes", session);
                logger.info("机器人启动中");
                return new NormalReturn(200, session);
            } catch (Exception e) {
                logger.error("进入房间失败", e);
                return new NormalReturn(500, "再试一次吧");
            }
        }
        return new NormalReturn(500, "房间不存在/登录失败");
    }

    @ResponseBody
    @GetMapping("/stopAll")
    public String stopAll() {
        allFlag = false;
        roomSet_in.clear();
        idSet.clear();
        return "stop success";
    }

    @ResponseBody
    @GetMapping("/getByPage")
    public String getByPage(String key, int page, int size, @RequestParam(name = "names", required = false) List<String> names, @RequestParam(name = "roomid", required = false) String roomid) {
        logger.info("查询key:{},page:{},size{},names:{},roomid:{}", key, page, size, names, roomid);
        if (!"TF".equals(key)) {
            Message msg = new Message();
            msg.setMessage("神秘暗号要输入的啦");
            List<Message> r = new ArrayList<>();
            r.add(msg);
            return JSONObject.toJSONString(new ReturnVo(0, r, 1));
        }
        if (names != null && names.size() > 0) {
            Page<Message> messages = messageService.selectBynames(page - 1, size, names);
            ReturnVo returnVo = new ReturnVo(0, messages.getContent(), (int) messages.getTotalElements());
            return JSONObject.toJSONString(returnVo);
        }
        if (roomid != null && roomid.length() > 0) {
            Page<Message> messages = messageService.findByRoomId(page - 1, size, roomid);
            return JSONObject.toJSONString(new ReturnVo(0, messages.getContent(), (int) messages.getTotalElements()));
        }
        Page<Message> msglist = messageService.msglist(page - 1, size);
        ReturnVo returnVo = new ReturnVo(0, msglist.getContent(), (int) msglist.getTotalElements());
        return JSONObject.toJSONString(returnVo);
    }

    @GetMapping("/welcomeStatus")
    @ResponseBody
    public NormalReturn welcomeFlag(String status) {
        RobotHandler.welComeFlag = "true".equals(status);
        return NormalReturn.SUCCESS.addMessage("欢迎状态：" + RobotHandler.welComeFlag);
    }

    @ResponseBody
    @GetMapping("/sessionlist")
    public String getAllsession() {
        return idSet.toString();
    }

    @Autowired
    public void setMessageService(MessageService messageService) {
        this.messageService = messageService;
    }

    @Autowired
    public void setHandlerService(HandlerService handlerService) {
        this.handlerService = handlerService;
    }
}